package com.stackoverflow;

import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;


public class QuestionList extends Activity implements OnClickListener {
	private QuestionGetter getQuestions;
	private String tagName;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.questionlist);
	    
	    tagName = getIntent().getStringExtra("tagName");
	    if (tagName != null && tagName.contains(",") && !tagName.contains("{user}"))
	    	tagName = tagName.substring(0, tagName.indexOf(","));
	    
		getQuestions = new QuestionGetter(QuestionList.this, (ListView) findViewById(R.id.questionlistview));
		getQuestions.setTag(tagName);
		getQuestions.execute();
		
		View nextButton = findViewById(R.id.nextpage);
        nextButton.setOnClickListener(this);
        
        View prevButton = findViewById(R.id.prevpage);
        prevButton.setOnClickListener(this);
        
        ListView mainListView = (ListView) findViewById(R.id.questionlistview);
        mainListView.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView adapterView, View view, int position, long id) {
            	// Get the question ID and pass it to the answer list activity
            	Intent i = new Intent(QuestionList.this, AnswerList.class);
            	SimpleAdapter adapter = (SimpleAdapter) adapterView.getAdapter();
            	HashMap map = (HashMap) adapter.getItem(position);
            	ListItem item = (ListItem) map.get("self");
            	i.putExtra("questionId", item.getId());
            	i.putExtra("questionBody", item.getText());
            	startActivity(i);
            }
        });
	}
	
	public void onClick(View v) {
		getQuestions = new QuestionGetter(QuestionList.this, (ListView) findViewById(R.id.questionlistview));
		getQuestions.setTag(tagName);
		switch (v.getId())
		{
			case(R.id.nextpage):
				if (Retriever.getInstance().incrementPage())
					getQuestions.execute();
				break;
			case(R.id.prevpage):
				if (Retriever.getInstance().decrementPage())
					getQuestions.execute();
				break;
		}
    }
}
